

import json
from logger_factory import logger

import datetime


'''-- 坐标名称
CREATE TABLE coordinate_name (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name VARCHAR(25) NOT NULL,
    -- 坐标
    coordinate VARCHAR(100), -- json格式 坐标为[[x1,y1],[x2,y2],[x3,y3],[x4,y4]]
    UNIQUE(name)
    -- 关联游戏页面
    game_page_id INTEGER NOT NULL,
    FOREIGN KEY(game_page_id) REFERENCES game_page(id)
);'''

class CoordinateNameMethod: # 坐标名称方法类


    def __init__(self, conn, cursor):

        self.conn = conn
        self.cursor = cursor

    def add_coordinate_name(self, name, coordinate: list):


        sql = "INSERT INTO coordinate_name (name, coordinate) VALUES (?,?)"
        try:
            self.cursor.execute(sql, (name, json.dumps(coordinate)))
            self.conn.commit()
            logger.info(f"add coordinate name {name} success")
            return True
        except Exception as e:
            logger.error(f"add coordinate name {name} failed, {e}")
            return False

    
    def get_coordinate_by_name(self, name):

        sql = "SELECT * FROM coordinate_name WHERE name=?"

        try:
            self.cursor.execute(sql, (name,))
            result = self.cursor.fetchone()

            if result:

                if result['coordinate']:

                    return json.loads(result['coordinate'])

            return None

        except Exception as e:
            logger.error(f"get coordinate by name {name} failed, {e}")
            return None

    # 查询指定页面所有坐标是否都已录入
    def is_all_coordinate_names_by_game_page_id(self, game_page_id):

        sql = "SELECT * FROM coordinate_name WHERE game_page_id=?"

        try:
            self.cursor.execute(sql, (game_page_id,))
            result = self.cursor.fetchall()

            for item in result:
                if not item['coordinate']:
                    return False

            return True

        except Exception as e:
            logger.error(f"is all coordinate names by game page id {game_page_id} failed, {e}")
            return False



# -- 成龙记录
# CREATE TABLE breeding_record (
#     id INTEGER PRIMARY KEY AUTOINCREMENT,
#     -- 龙种类型
#     dinosaur_type VARCHAR(25),
#     -- 养成时间
#     breeding_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
# );


class BreedingRecordMethod: # 成龙记录方法类


    def __init__(self, conn, cursor):

        self.conn = conn
        self.cursor = cursor

    def add_breeding_record(self, dinosaur_type):


        sql = "INSERT INTO breeding_record (dinosaur_type) VALUES (?)"
        try:
            self.cursor.execute(sql, (dinosaur_type,))
            self.conn.commit()
            logger.info(f"add breeding record {dinosaur_type} success")
            return True
        except Exception as e:
            logger.error(f"add breeding record {dinosaur_type} failed, {e}")
            return False
    
    def get_all_breeding_records(self, limit=10, offset=0):

        sql = "SELECT * FROM breeding_record LIMIT ? OFFSET ?"

        try:
            self.cursor.execute(sql, (limit, offset))
            result = self.cursor.fetchall()

            return result # 返回成龙记录列表

        except Exception as e:
            logger.error(f"get all breeding records failed, {e}")
            return None
        
    # 今天养了几条龙
    def get_today_breeding_count(self):

        sql = "SELECT COUNT(*) as count FROM breeding_record WHERE breeding_time >= ?"

        try:
            self.cursor.execute(sql, (datetime.datetime.now().strftime('%Y-%m-%d'),))
            result = self.cursor.fetchone()

            if result:
                return result['count']
            else:
                return 0

        except Exception as e:
            logger.error(f"get today breeding count failed, {e}")
            return None